package cn.fantasy.test;

/**
 * @author zhangliagn
 * @description 线程池创建
 * @date 2021/6/21 14:35
 * @Version V1.0
 */

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * corePoolSize : 核⼼线程数线程数定义了最⼩可以同时运⾏的线程数量。
 * maximumPoolSize : 当队列中存放的任务达到队列容量的时候，当前可以同时运⾏的线程数
 * 量变为最⼤线程数。
 * workQueue : 当新任务来的时候会先判断当前运⾏的线程数量是否达到核⼼线程数，如果达到
 * 的话，新任务就会被存放在队列中。
 */
public class ThrealPoolExecutorDemo {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 1L;

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        for (int i = 0; i < 100000; i++) {
            MyRunnable myRunnable = new MyRunnable("" + i);
            executor.execute(myRunnable);
        }

        executor.shutdown();
        while (!executor.isTerminated()) { }
        System.out.println("Finished all threads");
    }
}
